/*
 * @lc app=leetcode.cn id=541 lang=cpp
 *
 * [541] 反转字符串 II
 */

// @lc code=start
class Solution
{
public:
  string reverseStr(string s, int k)
  {
    int n = s.size(), step = k << 1;
    int group = n / step, r = n % step;
    // 反转2k的前k个
    for (int i = 0, j = 0; i < group; ++i, j += step)
      reverse(s, j, j + k - 1);
    
    if (r < k) // r < k
      reverse(s, n - r, n - 1);
    else // k <= r < 2k
      reverse(s, n - r, n - r + k - 1);
    return s;
  }

  inline void reverse(string& s, int begin, int end)
  {
    while (begin < end) {
      char tmp = s[begin];
      s[begin] = s[end];
      s[end]   = tmp;
      ++begin;
      --end;
    }
  }
};
// @lc code=end
